package com.bruce.codeFactory.practice;

import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;

/**
 * @author luotuan
 * @Description
 * @create 2019-03-20 15:17
 **/
public class Spec {
    private static final byte[] SALT = {'d','c','e','1'};
    public static byte[] getEncryptedPassword(
            String password,
            byte[] salt,
            int iterations,
            int derivedKeyLength
    ) throws NoSuchAlgorithmException, InvalidKeySpecException {
        KeySpec spec = new PBEKeySpec(
                password.toCharArray(),
                salt,
                iterations,
                derivedKeyLength * 8
        );

        SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");

        return f.generateSecret(spec).getEncoded();
    }
//    public String pbkdf2(String secret, String salt, int iterations, int keyLength) {
//        PKCS5S2ParametersGenerator gen = new PKCS5S2ParametersGenerator(new SHA256Digest());
//        byte[] secretData = secret.getBytes();
//        byte[] saltData = salt.getBytes();
//        gen.init(secretData, saltData, iterations);
//        byte[] derivedKey = ((KeyParameter)gen.generateDerivedParameters(keyLength * 8)).getKey();
//        return toHex(derivedKey);
//    }
    public static void main(String[] args) throws Exception {
        String password = "werwerre2342";
        byte[] resultByte = getEncryptedPassword(password,SALT,4096,256);
        String result = new String(resultByte);
        System.out.println(result);
    }
}
